package com.markerhub.service.impl;

import com.markerhub.common.lang.Result;
import com.markerhub.entity.DeliveryOrder;
import com.markerhub.exception.apiException.OrderException;
import com.markerhub.handler.UserThreadLocal;
import com.markerhub.mapper.OrderMapper;
import com.markerhub.mapper.UserMapper;
import com.markerhub.pojo.dto.UserDto;
import com.markerhub.service.OrderService;
import com.markerhub.util.UUIDUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

/**
 * @Author by MaXiaofeng
 * @Description 外卖柜实现方法
 * @Date 2022/2/16 21:29
 * @Version 1.0.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public Result makeOrder(int cabinet_id, String phone) throws OrderException {
        //从线程变量中获取外卖员信息
        UserDto userDto = UserThreadLocal.get();
        DeliveryOrder order = new DeliveryOrder();
        order.setOrder_createTime(new Timestamp(System.currentTimeMillis()));//订单的创始时间
        order.setOrder_customer_phone(phone);//存餐码——外卖下单手机号
        order.setOrder_staffId(userDto.getId());//外卖员id
        order.setOrder_number(UUIDUtils.getUUID());//生成订单号
        order.setOrder_state(0);//订单状态0
        order.setCabinet_id(cabinet_id);//外卖柜号1
        //检索该外卖柜可用的柜子
        Map<Integer, Integer> cabinetNum = new HashMap<>();
        List<HashMap<String, Integer>> usedCabinetNum = orderMapper.selectUsingCabinetNumber(cabinet_id);
        int index = 0;
        for (int i = 0; i < 30; i++) {
            boolean exist = false;
            for (int j = 0; j < usedCabinetNum.size(); j++) {
                if (i == (usedCabinetNum.get(j)).get("order_doorNum")) {
                    exist = true;
                    break;
                }
            }
            if (!exist) {
                cabinetNum.put(index++, i);
            }
        }
        //超出柜门 抛出异常
        if (cabinetNum.size() <= 0) {
            throw new OrderException();
        }
        int doorNum = cabinetNum.get(new Random().nextInt(cabinetNum.size()));
        order.setOrder_doorNum(doorNum);
        orderMapper.createOrder(order);
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("cabinetId", cabinet_id);
        responseMap.put("doorNum", doorNum);
        return Result.success("生成快递柜订单成功", responseMap);
    }

    @Override
    public Result closeCabinetByMan(int cabinet_id, int cabinet_doorNum) {
        if (orderMapper.updateTimeOfPutFood(new Timestamp(System.currentTimeMillis()), cabinet_id, cabinet_doorNum) >= 1) {
            return Result.success("外卖员放入外卖成功");
        }
        return Result.fail("外卖员放入外卖失败");
    }

    /**
     * 获取用户外卖的柜门集合
     *
     * @param phone
     * @return
     */
    @Override
    public Result takeFoodByCustomer(String phone) {
        //首先返回该用户的所有外卖所在的柜门集合
        List<Map<String, Object>> cabinetList = orderMapper.findByPhone(phone);
        if (cabinetList.size() >= 1) {
            //根据手机号查询用户id
            int userId = userMapper.selectUserIdByPhone(phone);
            //然后修改柜门状态
            if (orderMapper.updateTimeOfTakeFood(userId, phone, new Timestamp(System.currentTimeMillis())) >= 1) {
                return Result.success("外卖柜集合", cabinetList);
            }
        }
        return Result.fail(702, "客户无对应外卖订单");
    }

    /**
     * 检测顾客关闭外卖柜柜门，更改订单状态，订单结束
     *
     * @param cabinet_id
     * @param cabinet_doorNum
     * @return
     */
    @Override
    public Result closeDoorByCustomer(int cabinet_id, int cabinet_doorNum) {
        if (orderMapper.updateOrderByCloseDoorByCustomer(cabinet_id, cabinet_doorNum) >= 1) {
            String SuccMessage = "顾客关闭柜门，外卖柜为" + cabinet_id + "柜门号" + cabinet_doorNum + "订单结束";
            return Result.success(SuccMessage);
        }
        String errorMessage = "查询不到外卖柜为" + cabinet_id + "柜门号" + cabinet_doorNum + "的订单信息，请确认信息";
        return Result.fail(errorMessage);
    }

    @Override
    public Result getHistoryOrder(int userId) {
        List<Map<String, Object>> orderList = orderMapper.getHistoryOrder(userId);
        if (orderList.size() >= 1) {
            return Result.success("用户以往订单", orderList);
        }
        return Result.fail("该用户无以往历史订单");
    }
}
